package com.xianshijian.oauth.server.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.xianshijian.oauth.common.entity.OAuth;
import com.xianshijian.oauth.common.utils.JsonUtils;
import com.xianshijian.oauth.server.dao.ThirdPartyDao;
import com.xianshijian.oauth.server.entity.ThirdParty;

/**
 * 第三方Service
 *
 * @author lzj
 */
@Service
public class ThirdPartyService {
    @Autowired
    private ThirdPartyDao thirdPartyDao;
    @Autowired
    private StringRedisTemplate template;

    /**
     * 根据thirdPartyId查找ThirdParty
     *
     * @param thirdPartyId
     * @return
     */
    public ThirdParty findByThirdPartyId(String thirdPartyId) {
        return thirdPartyDao.findByThirdPartyId(thirdPartyId);
    }

    /**
     * 根据thirdPartySecret查找ThirdParty
     *
     * @param thirdPartySecret
     * @return
     */
    public ThirdParty findByThirdPartySecret(String thirdPartySecret) {
        return thirdPartyDao.findByThirdPartySecret(thirdPartySecret);
    }

    /**
     * 放入redis缓存
     *
     * @param redisKey
     * @param redisKeyMap
     */
    public void putCacheKey(String redisKey, Map<String, Object> redisKeyMap) {
        // FIXME 应该换成带过期的操作.不允许永久存储.
        ValueOperations<String, String> ops = this.template.opsForValue();
        ops.set(redisKey, JsonUtils.objectToJson(redisKeyMap));
    }

    /**
     * 获取redis缓存
     *
     * @param sessionId
     * @return
     */
    public Map<String, String> getCacheKey(String sessionId) {
        ValueOperations<String, String> ops = this.template.opsForValue();
        return JsonUtils.jsonToPojo(ops.get(sessionId), HashMap.class);

    }

    /**
     * 清除stamp
     *
     * @param redisKey
     * @param map
     */
    public void clearCacheKey(String redisKey, Map<String, String> map) {
        ValueOperations<String, String> ops = this.template.opsForValue();
        ops.set(redisKey, null);
    }

    /**
     * 清除stamp
     *
     * @param redisKey
     * @param map
     */
    public void clearStampCacheKey(String redisKey, Map<String, String> map) {
        map.put(OAuth.OAUTH_STAMP, null);
        ValueOperations<String, String> ops = this.template.opsForValue();
        ops.set(redisKey, JsonUtils.objectToJson(map));

    }


}
